<?php

use app\common\model\Category;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use fast\Form;
use fast\Tree;
use think\Db;

if (!function_exists('build_select')) {

    /**
     * 生成下拉列表
     * @param string $name
     * @param mixed  $options
     * @param mixed  $selected
     * @param mixed  $attr
     * @return string
     */
    function build_select($name, $options, $selected = [], $attr = [])
    {
        $options = is_array($options) ? $options : explode(',', $options);
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        return Form::select($name, $options, $selected, $attr);
    }
}

if (!function_exists('build_radios')) {

    /**
     * 生成单选按钮组
     * @param string $name
     * @param array  $list
     * @param mixed  $selected
     * @return string
     */
    function build_radios($name, $list = [], $selected = null)
    {
        $html = [];
        $selected = is_null($selected) ? key($list) : $selected;
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        foreach ($list as $k => $v) {
            $html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::radio($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
        }
        return '<div class="radio">' . implode(' ', $html) . '</div>';
    }
}

if (!function_exists('build_checkboxs')) {

    /**
     * 生成复选按钮组
     * @param string $name
     * @param array  $list
     * @param mixed  $selected
     * @return string
     */
    function build_checkboxs($name, $list = [], $selected = null)
    {
        $html = [];
        $selected = is_null($selected) ? [] : $selected;
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        foreach ($list as $k => $v) {
            $html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::checkbox($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
        }
        return '<div class="checkbox">' . implode(' ', $html) . '</div>';
    }
}


if (!function_exists('build_category_select')) {

    /**
     * 生成分类下拉列表框
     * @param string $name
     * @param string $type
     * @param mixed  $selected
     * @param array  $attr
     * @param array  $header
     * @return string
     */
    function build_category_select($name, $type, $selected = null, $attr = [], $header = [])
    {
        $tree = Tree::instance();
        $tree->init(Category::getCategoryArray($type), 'pid');
        $categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = $header ? $header : [];
        foreach ($categorylist as $k => $v) {
            $categorydata[$v['id']] = $v['name'];
        }
        $attr = array_merge(['id' => "c-{$name}", 'class' => 'form-control selectpicker'], $attr);
        return build_select($name, $categorydata, $selected, $attr);
    }
}

if (!function_exists('build_toolbar')) {

    /**
     * 生成表格操作按钮栏
     * @param array $btns 按钮组
     * @param array $attr 按钮属性值
     * @return string
     */
    function build_toolbar($btns = null, $attr = [])
    {
        $auth = \app\admin\library\Auth::instance();
        $controller = str_replace('.', '/', strtolower(think\Request::instance()->controller()));
        $btns = $btns ? $btns : ['refresh', 'add', 'edit', 'del', 'import'];
        $btns = is_array($btns) ? $btns : explode(',', $btns);
        $index = array_search('delete', $btns);
        if ($index !== false) {
            $btns[$index] = 'del';
        }
        $btnAttr = [
            'refresh' => ['javascript:;', 'btn btn-primary btn-refresh', 'fa fa-refresh', '', __('Refresh')],
            'add'     => ['javascript:;', 'btn btn-success btn-add', 'fa fa-plus', __('Add'), __('Add')],
            'edit'    => ['javascript:;', 'btn btn-success btn-edit btn-disabled disabled', 'fa fa-pencil', __('Edit'), __('Edit')],
            'del'     => ['javascript:;', 'btn btn-danger btn-del btn-disabled disabled', 'fa fa-trash', __('Delete'), __('Delete')],
            'import'  => ['javascript:;', 'btn btn-info btn-import', 'fa fa-upload', __('Import'), __('Import')],
        ];
        $btnAttr = array_merge($btnAttr, $attr);
        $html = [];
        foreach ($btns as $k => $v) {
            //如果未定义或没有权限
            if (!isset($btnAttr[$v]) || ($v !== 'refresh' && !$auth->check("{$controller}/{$v}"))) {
                continue;
            }
            list($href, $class, $icon, $text, $title) = $btnAttr[$v];
            //$extend = $v == 'import' ? 'id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"' : '';
            //$html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '" ' . $extend . '><i class="' . $icon . '"></i> ' . $text . '</a>';
            if ($v == 'import') {
                $template = str_replace('/', '_', $controller);
                $download = '';
                if (file_exists("./template/{$template}.xlsx")) {
                    $download .= "<li><a href=\"/template/{$template}.xlsx\" target=\"_blank\">XLSX模版</a></li>";
                }
                if (file_exists("./template/{$template}.xls")) {
                    $download .= "<li><a href=\"/template/{$template}.xls\" target=\"_blank\">XLS模版</a></li>";
                }
                if (file_exists("./template/{$template}.csv")) {
                    $download .= empty($download) ? '' : "<li class=\"divider\"></li>";
                    $download .= "<li><a href=\"/template/{$template}.csv\" target=\"_blank\">CSV模版</a></li>";
                }
                $download .= empty($download) ? '' : "\n                            ";
                if (!empty($download)) {
                    $html[] = <<<EOT
                        <div class="btn-group">
                            <button type="button" href="{$href}" class="btn btn-info btn-import" title="{$title}" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="{$icon}"></i> {$text}</button>
                            <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" title="下载批量导入模版">
                                <span class="caret"></span>
                                <span class="sr-only">Toggle Dropdown</span>
                            </button>
                            <ul class="dropdown-menu" role="menu">{$download}</ul>
                        </div>
EOT;
                } else {
                    $html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="' . $icon . '"></i> ' . $text . '</a>';
                }
            } else {
                $html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '"><i class="' . $icon . '"></i> ' . $text . '</a>';
            }
        }
        return implode(' ', $html);
    }
}

if (!function_exists('build_heading')) {

    /**
     * 生成页面Heading
     *
     * @param string $path 指定的path
     * @return string
     */
    function build_heading($path = null, $container = true)
    {
        $title = $content = '';
        if (is_null($path)) {
            $action = request()->action();
            $controller = str_replace('.', '/', request()->controller());
            $path = strtolower($controller . ($action && $action != 'index' ? '/' . $action : ''));
        }
        // 根据当前的URI自动匹配父节点的标题和备注
        $data = Db::name('auth_rule')->where('name', $path)->field('title,remark')->find();
        if ($data) {
            $title = __($data['title']);
            $content = __($data['remark']);
        }
        if (!$content) {
            return '';
        }
        $result = '<div class="panel-lead"><em>' . $title . '</em>' . $content . '</div>';
        if ($container) {
            $result = '<div class="panel-heading">' . $result . '</div>';
        }
        return $result;
    }
}

if (!function_exists('build_suffix_image')) {
    /**
     * 生成文件后缀图片
     * @param string $suffix 后缀
     * @param null   $background
     * @return string
     */
    function build_suffix_image($suffix, $background = null)
    {
        $suffix = mb_substr(strtoupper($suffix), 0, 4);
        $total = unpack('L', hash('adler32', $suffix, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $background = $background ? $background : "rgb({$r},{$g},{$b})";

        $icon = <<<EOT
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
            <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
            <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
            <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
            <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
            <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
            <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
        </svg>
EOT;
        return $icon;
    }
}

function getSelectText($tb_name,$value) {
    $field_names = '';
    $colunm_name = 'name';
    if($tb_name == "street" || $tb_name == 'leader'){
        $tb_name = 'admin';
        $colunm_name = 'nickname';
    }
    $where['id'] = ['in',$value];

    $name_arr = Db::name($tb_name)->where($where)->column($colunm_name);

    $field_names =  implode(",",$name_arr);

    return $field_names;
}

function getSelectId($tb_name,$value) {
    // echo $value;
    $field_names = '';
    $colunm_name = 'name';
    if($tb_name == 'leader'){
        $tb_name = 'admin';
        $colunm_name = 'nickname';
    }
    $where[$colunm_name] = ['in',$value];

    $id_arr = Db::name($tb_name)->where($where)->column('id');
    // var_dump(Db::name($tb_name)->getLastSql());
    $field_ids =  implode(",",$id_arr);
    // echo $field_ids;
    return $field_ids;
}


/**
 * 根据不同的用户类型获取用户
 * @param $tablename  用户类型
 * @param array $where  附加条件
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getSelectList($tablename, $where = []){
    $options = [];
    if("street" == $tablename) {
        $res = Db::name('admin')
            -> alias('a')
            -> field('a.id,a.nickname,a.nickname as name')
            -> join('auth_group_access b',"a.id=b.uid ")
            -> where(['b.group_id' =>['in',[GROUP_DISTRICTUNIT, GROUP_STREET]]])
            -> select();
    }
    elseif("leader" == $tablename){
        $res = Db::name('admin')
            -> alias('a')
            -> field('a.id,a.nickname,a.nickname as name')
            -> join('auth_group_access b',"a.id=b.uid ")
            -> where(['b.group_id' => GROUP_LEADER,'a.is_select'    => 1])
            -> select();
    }elseif("command_type" == $tablename){
        $res = Db::name('command_type')
            -> alias('a')
            -> field('a.id,a.name')
            -> select();
    }elseif("carrier" == $tablename){
        $res = Db::name('carrier') -> where($where) -> select();
    }
    else{
        $res = Db::name($tablename)->where($where)->order('weigh')->select();
    }

    foreach ($res as $kk=> $vv) {
        $options[$vv['id']] = $vv['name'];
    }
    return $options;
}



if(!function_exists('exportExcel')) {
    /**
     * 输出到浏览器(需要设置header头)
     * @param string $fileName 文件名
     * @param string $fileType 文件类型
     */
    function exportExcel($fileName, $fileType ,$data,$title)
    {

        //文件名称校验
        if (!$fileName) {
            trigger_error('文件名不能为空', E_USER_ERROR);
        }

        //Excel文件类型校验
        $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];
        if (!in_array($fileType, $type)) {
            trigger_error('未知文件类型', E_USER_ERROR);
        }

        $ext = '';

        if ($fileType == 'Excel2007' || $fileType == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . date('Y-m-d') . '.xlsx"');
            header('Cache-Control: max-age=0');
            $ext = 'Xlsx';
        } else { //Excel5
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $fileName . date('Y-m-d') . '.xls"');
            header('Cache-Control: max-age=0');
            $ext = 'Xls';
        }


        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();

        //设置工作表标题名称
        // $worksheet->setTitle('签约库');

        $worksheet->getColumnDimension('A')->setWidth(10);
        // $worksheet->getColumnDimension('B')->setWidth(25);
        $worksheet->getDefaultColumnDimension()->setWidth(30);


        //表头
        //设置单元格内容
        $i = 1;
        foreach ($title as $key => $value) {
            $worksheet->setCellValueByColumnAndRow($i ++, 1, $value);
        }
        $row = 2; //从第二行开始
        foreach ($data as $item) {
            $column = 1;

            foreach ($title as $k => $value) {

                $worksheet->setCellValueByColumnAndRow($column, $row, $item[$k]);
                $column++;
            }
            $row++;
        }


        $worksheet->getStyle('A1:'.Coordinate::stringFromColumnIndex($column-1).'1')->getFont()->setBold(true);
        $styleArray = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                // 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
                // 'wrapText' => true,
            ],
        ];
        $worksheet->getStyle('C1:'.Coordinate::stringFromColumnIndex($column-1).($row-1))->applyFromArray($styleArray);


        $writer = IOFactory::createWriter($spreadsheet,$ext);
        $writer->save('php://output');
    }



}
if(!function_exists('getProjectRequieredText')) {
    function getProjectRequieredText(\app\admin\model\Project $row) {
        $where['table_name'] = 'project';
        $where['status'] = 1;
        // $where['item_library'] = ['in',"0,{$library_id}"];
        $fields_list = Db::name('fields')->where($where)->select();

        $required_arr = [];
        foreach ($fields_list as $key => $value) {
            if(isset($row["tmp_{$value['item_id']}"]) && $row["tmp_{$value['item_id']}_status"] == STATUS_SUBMIT)
            {
                // echo $value['item_id'];
                $status ++;
            }

            if(isset($row["tmp_{$value['item_id']}"]) && $row["tmp_{$value['item_id']}_status"] == STATUS_REJECT)
            {
                // echo $value['item_id'];
                $reject_status ++;
            }

            $item_required = $value['item_required'] ? json_decode($value['item_required'],true):'';
            if(isset($row['library_id']) && $row['library_id'] && $item_required )
            {
                $is_required = $item_required[$row['library_id']]['is_required'];

                if($is_required == '1'   && $value['item_class'] != 'capital' && $value['item_class'] != 'agreement')
                {

                    if(!$row[$value['item_id']] && !$row['tmp_'.$value['item_id']])
                        $required_arr[] = $value['item_label'];

                }
            }
        }
        if(!$row['domestic_capital'] && !$row['tmp_foreign_capital'] && !$row['tmp_domestic_capital'] && !$row['foreign_capital'])
            $required_arr[] = '内外资(至少填一项)';



        if(isset($row['library_id']) && $row['library_id']==2)
        {
            if((!$row['carrier_id'] && $row['carrier_id'] != 5 && !$row['carrier_id_relation']) && ($row['tmp_carrier_id'] && $row['tmp_carrier_id'] != 5 && !$row['tmp_carrier_id_relation']))
                $required_arr[] = '载体面积';

            if(($row['is_access'] == '是' &&  !$row['access_time'])|| ($row['tmp_is_access'] == '是' &&  !$row['tmp_access_time']))
                $required_arr[] = '准入时间';
            if(($row['is_land'] == '是' &&  !$row['land_time']) ||  ($row['tmp_is_land'] == '是' &&  !$row['tmp_land_time']))
                $required_arr[] = '拿地时间';

            if(!$row['framework_agreement_time'] && !$row['invesment_agreement_time'] && !$row['tmp_framework_agreement_time'] && !$row['tmp_invesment_agreement_time'])
                $required_arr[] = '框架、正式协议(至少填一项)';
        }

        $required_text = implode(",",$required_arr);
        return $required_text;

    }
}


if(!function_exists('getIsImportant')) {
    function getIsImportant($arr) {
        $major_activity = (new \app\admin\model\Activity)->where(['is_important'=>1])->column('id');

        $is_important = 0;
        if(is_array($arr))
        {

            $result = array_intersect($major_activity,$arr);
            if($result)
                $is_important = 1;
        }

        return $is_important;


    }
}

